package com.runa.rccprotocol.em;

import com.runa.persistence.StringUtil;
import com.runa.protocol.util.ByteUtil;
import com.runa.protocol.util.DigitalUtil;

/**
 * 2024/8/28 10:15
 * zhangYB
 */
public enum ApportionCollectorModbusTypeEnum {

    HZ("HZ", (byte)0x03),
    HWZ("HWZ", (byte)0x03),
    PG("PG", (byte)0x04),
    TG("TG-D25", (byte)0x03),
    XBK("XBK-01", (byte)0x03);

    private String value;
    private byte functionCode;

    ApportionCollectorModbusTypeEnum(String value, byte functionCode) {
        this.value = value;
        this.functionCode = functionCode;
    }

    public static byte[] getModbusBytes(Integer slaveId, String model) {
        ApportionCollectorModbusTypeEnum v = getInstance(model);
        byte[] bs = new byte[8];
        int index = 0;
        bs[index++] = (byte)(slaveId & 0xff);
        bs[index++] = v.functionCode;
        byte[] bytes = {};
        switch (v) {
            case HZ:
                bytes = new byte[]{0x00, 0x00, 0x00, 0x11};
                break;
            case HWZ:
                bytes = new byte[]{0x00, 0x00, 0x00, 0x1C};
                break;
            case PG:
                bytes = new byte[]{0x00, 0x63, 0x00, 0x24};
                break;
            case TG:
                bytes = new byte[]{0x00, 0x00, 0x00, 0x02};
                break;
            case XBK:
                bytes = new byte[]{0x00, 0x01, 0x00, 0x34};
                break;
        }
        for (int i = 0; i < bytes.length; i++) {
            bs[index++] = bytes[i];
        }
        int crc = DigitalUtil.calcCrc16(bs, 6);
        bs[index++] = (byte) (crc & 0xff);
        bs[index++] = (byte) (crc >> 8);
        return bs;
    }

    public static void main(String[] args) {
        byte[] pgs = getModbusBytes(1, "PG");
        System.out.println(ByteUtil.byteToHexString(pgs));
    }



    public static ApportionCollectorModbusTypeEnum getInstance(String model) {
        for (ApportionCollectorModbusTypeEnum value : values()) {
            if (model.equalsIgnoreCase(value.value)) {
                return value;
            }
        }
        return null;
    }

    public static boolean contains(String model) {
        if (StringUtil.isBlank(model)) {
            return false;
        }
        for (ApportionCollectorModbusTypeEnum value : values()) {
            if (model.equalsIgnoreCase(value.value)) {
                return true;
            }
        }
        return false;
    }

    public static byte functionCode(String model) {
        ApportionCollectorModbusTypeEnum v = getInstance(model);
        return v.functionCode;
    }


}
